package com.youth.platform.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.youth.framework.core.InvokeResult;
import com.youth.platform.entity.RegisterInfo;
import com.youth.platform.validator.RegisterValidator;

@Controller
@RequestMapping("/register")
public class RegisterController {

	@InitBinder("registerInfo")
	protected void initBinder(WebDataBinder binder) {
		binder.setValidator(new RegisterValidator());
	}

	@RequestMapping(value = "/index.html")
	public String index() {
		return "user/register";
	}

	@RequestMapping(value = "/create.do", method = RequestMethod.POST)
	public String create(
			@Valid @ModelAttribute("registerInfo") RegisterInfo info,
			BindingResult result, RedirectAttributes attr) {

		if (result.hasErrors()) {
			attr.addFlashAttribute(BindingResult.MODEL_KEY_PREFIX
					+ "registerInfo", result);
			return "redirect:/register/index.html";
		}

		return "user/register_result";
	}

	@RequestMapping(value = "/create.json")
	public @ResponseBody Object createJson(
			@Valid @ModelAttribute("registerInfo") RegisterInfo info,
			BindingResult result) {
		InvokeResult<Object> ir = new InvokeResult<Object>();
		if (result.hasErrors()) {
			List<ObjectError> allErrors = result.getAllErrors();
			ir.setSuccessful(false);
			ir.setValue(allErrors);
			ir.setMessage(result.toString());
			return ir;
		}

		ir.setSuccessful(true);
		return ir;
	}

}
